/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cassandrawindow;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.crypto.Mac;

public class HandleDataTableBannerDateV3 {
    
    public static final String KEYSPACE                             =   "AdsData";
    public static final String ColumFamly                           =   "BannerViewCountCf";
    public static final String ColumFamlyBannerClickCountCf         =   "BannerClickCountCf";
    public static final String ColumFamlyBannerViewCountCf          =   "BannerViewCountCf";

    public static final String ColumFamlyCampaignClickCountCf       =   "CampaignCountCf";
    public static final String ColumFamlyCampaignViewCountCf        =   "CampaignViewCountCf";
    
     public static final String ColumFamlyDateBanner_Geo_Counter    =   "DateBanner_Geo_Counter";
    
    public void handleData() throws ParseException, InterruptedException, ClassNotFoundException, InstantiationException, IllegalAccessException
    {
        
        CassandraAction cassAct = new CassandraAction(ACCOUNT.CLUSTERNAME ,ACCOUNT.URL, ACCOUNT.PORT);
        cassAct.initReadWirte(KEYSPACE);
        
        MysqlDataManagerMain mysqlMain = new MysqlDataManagerMain();
        String currentDate = HandleDataTableDomainDate.handleDate();//2012-07-24
        
        //String currentDate = "2013-08-12";     
        long first_time = System.currentTimeMillis();               
        MysqlDataManager mysqldatamanager = new MysqlDataManager();
        
        //get banner type
        Map<String,String> bannerType=new HashMap<>();
        bannerType = mysqldatamanager.getBannerTypeDataMobile();
        
        //get all fraud click by date
        Map<String, Integer> fraudclicks = new HashMap<>();       
        //fraudclicks = mysqldatamanager.getAllFraudClickByBannerid(currentDate);
        /*
         * Lấy dữ liệu tiền của banner theo ngay
         */
        Map<String, Integer> MoneyByBanner = new HashMap<>();
        MoneyByBanner = mysqldatamanager.getMoneyByBannerId(currentDate);
        
        //lấy budget theo ngày đối với mỗi campaignid
        Map<Integer, Long> MaxValue = new HashMap<>();
        MaxValue = mysqlMain.getMaxValueDaybyBannerIdMobile(currentDate);        
        
        //tinh vung miền đối với mỗi  banner     
        Map<String, String> geoMap = new HashMap<>();
        geoMap = HandleDataGeo.handleData();       
        /*
         * Lấy dữ liệu uv,uc đối với mỗi banner
         */
        Map<Integer, String> uv_uc = new HashMap<>();           
        uv_uc = mysqlMain.getUvUcByBanneridMobile(currentDate);    
        
        //lấy tất cả các banid và campaignid tương ứng(kiểu MAP: banid : campid )
        Map<String, String> banAndCamp = new HashMap<>();
        banAndCamp = mysqlMain.getBannerIDandCapmIDByMobile();        
        /*
         * Lấy dữ liệu click và money đối với mỗi campaign
         */
        Map<String, String> ClickAndMoneyByCamp = new HashMap<>();
        ClickAndMoneyByCamp = mysqldatamanager.getClickByCampaignid(currentDate);
        
        //lay du lieu click ,view,money vỡi mỗi banner từ  bang domain
        Map<String, String> dataFromTableDomain = new HashMap<>();                
        dataFromTableDomain = mysqldatamanager.getClickByDomainDateMobile(currentDate);
        
        StringBuilder sbff = new StringBuilder();
        Iterator iterator = dataFromTableDomain.entrySet().iterator();        
	while (iterator.hasNext()) {
            Map.Entry mapEntry = (Map.Entry) iterator.next();            
            String key = (String) mapEntry.getKey();
            String value = (String) mapEntry.getValue();
            String bannerid     = key.split("_")[0];                
            if(banAndCamp.containsKey(bannerid))
            {
                String camid        = banAndCamp.get(bannerid);

                //String bannerid     = "187589";
                //if(camid.equals("1033638")){
                String totalclick   = value.split("_")[0];
                String totalview    = value.split("_")[1];
                String money        = value.split("_")[2];
                String geoValue     = geoMap.get(bannerid);
                String banner_type = bannerType.get(bannerid); 
                String str = getDataCampaignAndBannerID(currentDate, camid, bannerid,Integer.valueOf(totalclick),Integer.valueOf(totalview),Integer.valueOf(money),fraudclicks,MoneyByBanner,MaxValue,uv_uc,geoValue,ClickAndMoneyByCamp,banner_type);
                sbff.append(str);  
                //}
            }                                                               
	}                        
        
        //xu li cho du lieu cuoi
        if(sbff.toString().length() > 1)
        {           
            String relStr = sbff.toString();
            String valInsert = relStr.substring(0, (relStr.length()-1));
            
            HandleImportData hid = new HandleImportData();
            String pathFile="";
            try {
                pathFile = hid.outToCsvBanner(valInsert);
                Debug.println("pathFile:"+pathFile);
            } catch (IOException ex) {
                ex.printStackTrace();
            }

            try {
                mysqldatamanager.removeDataBannerByDate(currentDate);                 
                mysqldatamanager.loadToV3BanDateFromFile(pathFile);
                             
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        
        //close connction to db
        mysqldatamanager.shutdownConnection();
        mysqlMain.shutdownConnection();         
        
        long last_time = System.currentTimeMillis();
        Debug.println("Thoi gian chay  :" +(last_time-first_time));
        Debug.println("success HandleDataTableBannerDate");

    }
    public static void removeDuplicateWithOrder(ArrayList arlList)
    {
        Set set = new HashSet();
        List newList = new ArrayList();
        for (Iterator iter = arlList.iterator(); iter.hasNext(); ) {
            Object element = iter.next();
            if (set.add(element))
            newList.add(element);
        }
        arlList.clear();
        arlList.addAll(newList);
    }
    public static String getDataCampaignAndBannerID(String currentDay,String camId,String banId,int totalclick,int totalview,int money,Map<String, Integer> fraudclicks,Map<String, Integer> MoneyByBanner,Map<Integer, Long> MaxValue,Map uv_uc,String geoValue,Map<String, String> ClickAndMoneyByCamp,String bannerType) throws ParseException
    {
            StringBuilder sb = new StringBuilder();            
            int clickCharge = 0 ;
            int viewCharge = 0 ;
            int fraud_click = 0 ;
            String uc ="";
            String uv ="";
            String mb = "";
            String mt = "";
            String mn = "";
            String other = "";
          
            if(uv_uc.containsKey(Integer.valueOf(banId)))
            {
                String uValue = (String) uv_uc.get(Integer.valueOf(banId));
                uc = uValue.split("_")[0];
                uv = uValue.split("_")[1];
            } else {
                uc = "0";
                uv = "0";
            }
            if(geoValue != null)
            {
                mb = geoValue.split("_")[0];
                mt = geoValue.split("_")[1];
                mn = geoValue.split("_")[2];
                other = geoValue.split("_")[3];                
            } else{
                mb = "0";
                mt = "0";
                mn = "0";
                other = "0";
            }
           
            if(ClickAndMoneyByCamp.containsKey(camId+"_"+currentDay) && camId.equals("1038956")){
                
                String clickbyCamp = ClickAndMoneyByCamp.get(camId+"_"+currentDay);
                String[] valueCap = new String[2];
                valueCap = clickbyCamp.split("_");
                //money cua campaignid
                int moneyByCamID = Integer.valueOf(valueCap[2]);
                long maxValueDay = 0;
                
                if(MaxValue.containsKey(Integer.valueOf(camId)))
                {
                    maxValueDay = MaxValue.get(Integer.valueOf(camId));
                }
                
                long moneyByBannerid = 0;

                if(MoneyByBanner.containsKey(banId)){
                    moneyByBannerid = MoneyByBanner.get(banId);   
                }
                
                if(moneyByCamID >= 1.2*maxValueDay)
                {
                    float sum = Float.valueOf(mb) +Float.valueOf(mn) +Float.valueOf(mt) +Float.valueOf(other);
                    //so du se dung de tinh clickcharge
                    long diffMoney = (long) (moneyByCamID - 1.2 * maxValueDay);
                    
                    long moneyCharge = 0 ; 
                    if("1".equals(bannerType))
                    {
                        //tinh toan clickcharge
                        clickCharge = getClickChargeByBannerid(diffMoney, currentDay,Integer.valueOf(camId), totalclick,totalview,ClickAndMoneyByCamp,bannerType);
                        if(totalclick != 0){                          
                            moneyCharge = (moneyByBannerid*(totalclick - clickCharge))/totalclick;                        
                        } else {
                            moneyCharge = 0;
                        }
                    } else if("2".equals(bannerType)){
                        //tinh toan viewcharge
                        viewCharge = getClickChargeByBannerid(diffMoney, currentDay,Integer.valueOf(camId),totalclick, totalview,ClickAndMoneyByCamp,bannerType);
                        if(totalview != 0){                          
                            moneyCharge = (moneyByBannerid*(totalview - viewCharge))/totalview;                        
                        } else {
                            moneyCharge = 0;
                        }
                    }
                    
                                                             
                    if(sum == 0)
                    {
                        String insertData = "('" + camId + "'," + banId +"," + totalclick +"," + (totalclick) +","+ (totalclick-clickCharge) +","+ (totalview-viewCharge) + "," + (totalview-viewCharge) +","+ Integer.valueOf(uc) + "," + Integer.valueOf(uv) +",0,0,0,0,'" + currentDay + "'," + moneyCharge +")";
                        sb.append(insertData).append(",");
                    } else {
                        DecimalFormat df = new DecimalFormat("0.0#");

                        String mienbac = df.format(Float.valueOf(mb)/sum*100);
                        String mientrung = df.format(Float.valueOf(mt)/sum*100);
                        String miennam = df.format(Float.valueOf(mn)/sum*100);
                        String remain = df.format(Float.valueOf(other)/sum*100);

                        String insertData = "('" + camId + "'," + banId +"," + totalclick +"," + (totalclick) +","+ (totalclick-clickCharge) +","+ (totalview-viewCharge) + "," + (totalview-viewCharge) +","+ Integer.valueOf(uc) + "," + Integer.valueOf(uv) +","+ mienbac+","+ mientrung+","+ miennam+","+ remain +",'" + currentDay + "'," + moneyCharge +")";
                        sb.append(insertData).append(",");
                    }
                } else{
                    float sum = Float.valueOf(mb) +Float.valueOf(mn) +Float.valueOf(mt) +Float.valueOf(other);
                    if(sum == 0)
                    {
                        String insertData = "('" + camId + "'," + banId +"," + totalclick +"," + (totalclick) +","+ (totalclick-clickCharge) +","+ totalview + "," + totalview +","+ Integer.valueOf(uc) + "," + Integer.valueOf(uv) +",0,0,0,0,'" + currentDay + "'," + moneyByBannerid +")";
                        sb.append(insertData).append(",");
                    } else{
                        DecimalFormat df = new DecimalFormat("0.0#");

                        String mienbac = df.format(Float.valueOf(mb)/sum*100);
                        String mientrung = df.format(Float.valueOf(mt)/sum*100);
                        String miennam = df.format(Float.valueOf(mn)/sum*100);
                        String remain = df.format(Float.valueOf(other)/sum*100);

                        String insertData = "('" + camId + "'," + banId +"," + totalclick +"," + totalclick +","+ (totalclick-clickCharge) +","+ totalview + "," + totalview +","+ Integer.valueOf(uc) + "," + Integer.valueOf(uv) +","+ mienbac+","+ mientrung+","+ miennam+","+ remain +",'" + currentDay + "'," + moneyByBannerid +")";
                        sb.append(insertData).append(",");
                    }
                } 
            } 
                                    
            //mysqldatamanager.insertDataCampaignAndBanner(String.valueOf(camId),String.valueOf(banId), String.valueOf(countClick), String.valueOf(countView), (prefixDB +i));
            return sb.toString();
    }
    
    /*
     * totalMoney : lượng tiền chênh lệch giữa overbudget và tiền ban dau
     *
     */
    public static int getClickChargeByBannerid(long totalMoney,String currentDay,int campid,int realclick,int viewcharge,Map<String, String> ClickAndMoneyByCamp,String bannertype)
    {        
        int retValue    = 0;
        int ret         = 0;
        String clickbyCamp = ClickAndMoneyByCamp.get(campid+"_"+currentDay);
        String[] valueCap = new String[2];
        valueCap = clickbyCamp.split("_");
        int click = Integer.valueOf(valueCap[0]);
        int view = Integer.valueOf(valueCap[1]);
        int money = Integer.valueOf(valueCap[2]);
        
        if("1".equals(bannertype)){
            if(money != 0){            
                retValue = (int)(totalMoney*click/money);//so click charge theo campaing
                ret = (int) (retValue*realclick/click);//so click charge theo bannerid  
            }
        } else if("2".equals(bannertype)){                        
                retValue = (int)(totalMoney*view/money);//so click charge theo campaing
                ret = (int) (retValue*viewcharge/view);//so click charge theo bannerid  
        }
        return ret;     
    }                                                                                                                                                                                                                                                                                                                                                                                                                                  
           
}
